<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted } from 'vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted } from 'vue'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { ref } from 'vue'
import { getConsultOrderDetail as getConsultOrderDetailAPI } from '@/services/consult'
import type { ConsultOrderItem } from '@/types/consult'
import { nextTick } from 'vue'

let socket: Socket
const userStore = useUserStore()
const route = useRoute()

const consult = ref({} as ConsultOrderItem)

const getConsultOrderDetail = async () => {
  const r = await getConsultOrderDetailAPI(route.query.orderId as string)
  consult.value = r.data
}

// 总的消息
const list = ref<Message[]>([])
onMounted(() => {
  // 创建一个 websocket 实例
  // 参数 1：后端提供的基地址
  // 参数 2：配置对象
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${userStore.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect')
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log('error', event)
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })

  // !获取默认的聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // data 是一个数组，数组里面是一个一个的对象，这个对象就表示某一个时间段之内的所有的消息
    // [{ createTime: "2023-07-26 8:17:33" }, { createTime: "2023-07-26 10:17:33" }]
    // [{ createTime: "2023-07-26 10:17:33" }, { createTime: "2023-07-26 12:17:33" }]
    // 目标 => 生成这样的格式 => [{ 专门显示时间的 }, ...data.items]
    const arr: Message[] = []
    data.forEach((item) => {
      arr.push({
        // 用创建时间当作 ID
        id: item.createTime,
        // 消息类型，MsgType.Notify 表示通用通知，值是 31
        msgType: MsgType.Notify,
        createTime: item.createTime,
        // msg 里面的 content 就是我们后续用来渲染的内容
        msg: { content: item.createTime }
      })
      // 把其他的消息也装进数组
      arr.push(...item.items)
    })
    // 越早的消息越添加到上面
    list.value.unshift(...arr)
  })

  getConsultOrderDetail()

  // 医生那边状态变了，例如结束问诊，就会触发 statusChange，我们这儿重新调用了 getConsultOrderDetail
  socket.on('statusChange', getConsultOrderDetail)

  // receiveChatMsg 可以监听到自己发的消息和医生回复的消息
  socket.on('receiveChatMsg', async (event) => {
    list.value.push(event)
    await nextTick()
    window.scroll(0, document.documentElement.scrollHeight)
  })
})

// 组件销毁的时候关闭 websocket 链接，节省资源占用
onUnmounted(() => {
  socket.close()
})

const sendText = (msg: string) => {
  socket.emit('sendChatMsg', {
    // 发送人
    from: userStore.user?.id,
    // 收消息人
    to: consult.value?.docInfo?.id,
    // 消息类型
    msgType: MsgType.MsgText,
    // 消息内容
    msg: { content: msg }
  })
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <!-- 顶部状态栏 -->
    <room-status
      v-if="consult.id"
      :status="consult.status"
      :countdown="consult.countdown"
    />
    <!-- 消息组件 -->
    <room-message :list="list" />
    <!-- 底部操作区 -->
    <!-- 不等于问诊中就禁用 -->
    <room-action
      @send-text="sendText"
      :disabled="consult.status !== OrderType.ConsultChat"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);

  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
